<template>
	<view class="chat-container">
		
			
		
			<!-- 顶部标题栏 -->
			<view class="header">
				
					<u-icon  name="arrow-left" color="#2979ff" size="28" @tap="handleClose"></u-icon>
					<text class="header-title">客服聊天</text>
			</view>
	
		<!-- 聊天消息显示区域 -->
		<scroll-view class="chat-messages" :scroll-y="true" scroll-with-animation>
			<view v-for="(message, index) in getRecordMessage" :key="index" :id="'message-' + index"
				:class="[message.role === '用户' ? 'agent-wrapper'  : 'customer-wrapper']">

				<!-- 客服消息 -->
				<template v-if="message.role !== '客服'">

					<view class="message agent">
						<text class="message-text">{{ message.msg }}</text>
					</view>
					<image class="avatar" :src="userImage"></image>
				</template>

				<!-- 用户消息 -->
				<template v-else>
					<image class="avatar" src="../../static/客服头像.png"></image>
					<view class="message customer">
						<text class="message-text">{{ message.msg }}</text>
					</view>

				</template>
			</view>
		</scroll-view>

		<!-- 输入框和发送按钮（固定在底部） -->
		<view class="input-container">
			<input v-model="inputMessage" class="message-input" placeholder="请输入消息..." />
			<button class="send-button" @click="sendMessage">发送</button>
		</view>
	</view>
</template>

<script>
	import {
		getRecord,
		getuser,
		svaeMessage,

	} from "@/api/user.js"
	export default {
		data() {
			return {
				websocket: null,
				userImage: "",
				getRecordMessage: [],
				inputMessage: '', // 用户输入的消息
				kefuId: null,
				messages: {
					id: this.$cookies.get("id"),
					msg: this.inputMessage,
					customerserviceId: this.kefuId,
					role: '用户'
				}, // 聊天消息记录
				kefu: false,
				kefu1: false,
				nokefu: false,
				sendMessage1: {
					id: this.$cookies.get("id"),
					msg: this.inputMessage,
					targetId: this.kefuId,
					role: "用户"
				}
			};
		},
		methods: {
			handleClose(){
				 // this.websocket.close();
				uni.switchTab({
					url:'/pages/profile/profile'
				})
				// this.websocket.onClose();
				
			},
			handleme(message) {
				if (message == "转人工") {
					if (this.kefu == true) {
						this.getRecordMessage.push({
							userId: this.$cookies.get("id"),
							msg: this.inputMessage,
							status: "未读",
							customerserviceId: "",
							role: "用户"
						})
						this.messages = {
								id: this.$cookies.get("id"),
								msg: message,
								customerserviceId: null,
								role: '用户'
							}, // 聊天消息记录
							svaeMessage(this.messages).then(res => {
								if (res.message == "success") {}
							})
						this.getRecordMessage.push({
							userId: this.$cookies.id,
							msg: "您当前就在人工请反馈您的问题，客服会给您及时回答",
							status: "未读",
							customerserviceId: "",
							role: "客服"
						})
						return false
					} else {
						alert("1111")
						this.getRecordMessage.push({
							userId: this.$cookies.get("id"),
							msg: this.inputMessage,
							status: "未读",
							customerserviceId: "",
							role: "用户"
						})
						this.getRecordMessage.push({
							userId: this.$cookies.get("id"),
							msg: "正在为您接人工",
							status: "未读",
							customerserviceId: "",
							role: "客服"
						})
						// 获取 WebSocket 连接的地址
						this.wsUrl = `ws://localhost:8080/websocket/${this.$cookies.get("id")}/用户`;

						// 连接到 WebSocket
						this.websocket = uni.connectSocket({
							url: this.wsUrl, // WebSocket 服务地址
							header: {
								'content-type': 'application/json'
							},
							success: () => {
								console.log("WebSocket 已连接");
							},
							fail: () => {
								console.log("WebSocket 连接失败");
							}
						});

						// 监听 WebSocket 打开事件
						this.websocket.onOpen(() => {
							console.log("WebSocket 连接已打开");
						});

						// 监听消息接收事件
						this.websocket.onMessage((message) => {
							console.log("消息" + message.data)
							this.sendMessage1 = JSON.parse(message.data)
							if (this.sendMessage1.msg == "没有客服在线") {
								this.getRecordMessage.push({
									userId: this.$cookies.id,
									msg: "当前没有客服在线，客服上班时间点为9：00-12：00，14：00-18：00,请耐心等待如有客服上线会自动连接",
									status: "未读",
									customerserviceId: "",
									role: "客服"
								})
								this.kefu1 = false
							} else if (this.sendMessage1.msg == "客服连接成功") {

								this.getRecordMessage.push({
									userId: this.$cookies.get("id"),
									msg: "当前工号为" + this.sendMessage1.targetId + "正在为您服务",
									status: "未读",
									customerserviceId: "",
									role: "客服"
								})
								this.kefuId = this.sendMessage1.targetId
								this.kefu1 = true
								this.kefu = true
							} else {
								this.getRecordMessage.push({
									userId: this.$cookies.get("id"),
									msg: this.sendMessage1.msg,
									status: "未读",
									customerserviceId: "",
									role: "客服"
								})
							}
						});
						// 监听 WebSocket 错误事件
						this.websocket.onError((error) => {
							console.log("WebSocket 错误：", error);
						});
						//监听 WebSocket 关闭事件
						this.websocket.onClose(() => {
							console.log("WebSocket 连接关闭");
						});
						return false;
					}
				} else {
					return true;
				}
			},
			sendMessage() {
				var b = this.handleme(this.inputMessage)
				if (b == true && this.kefu1 == false) {
					this.getRecordMessage.push({
						userId: this.$cookies.get("id"),
						msg: this.inputMessage,
						status: "未读",
						customerserviceId: "",
						role: "用户"
					})
					this.messages = {
							id: this.$cookies.get("id"),
							msg: this.inputMessage,
							customerserviceId: null,
							role: '用户'
						}
						var data={
							userId: this.$cookies.get("id"),
							msg: this.inputMessage,
							customerserviceId: null,
							role: '用户'
						}
						svaeMessage(data).then(res => {
							if (res.message == "success") {}
						})
				} else if (b == true && this.kefu1 == true) {
					this.getRecordMessage.push({
						userId: this.$cookies.get("id"),
						msg: this.inputMessage,
						status: "未读",
						customerserviceId: "",
						role: "用户"
					})
					this.sendMessage1 = {
						"id": `${this.$cookies.get("id")}`,
						"msg": `${this.inputMessage}`,
						"targetId": `${this.kefuId}`,
						"role": "用户",
						"timestamp":new Date().toISOString()
					}

					console.log(JSON.stringify(this.sendMessage1))
					var a = JSON.stringify(this.sendMessage1)
					this.websocket.send({
						data: a
					})
				}

				this.inputMessage = ""
			},

		},
		
		onUnload(){
			uni.closeSocket()
		},

		onLoad() {
			getRecord({
				userId: this.$cookies.get("id")
			}).then(res => {
				if (res.message == "false") {

				} else {
					this.getRecordMessage = res.data

				}
			})
			getuser({
				userId: this.$cookies.get("id")
			}).then(res => {
				this.userImage = res.data.userImage
			})
		},

	};
</script>


<style scoped>
	.chat-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 60px;
	}

	.header {
	  display: flex;
	  background-color: #2ac2d2;
	  padding: 15px;
	  align-items: center; /* 垂直居中 */
	  color: #fff;
	}
	
	.header-title {
	  flex-grow: 1; /* 使标题占据剩余空间 */
	  text-align: center; /* 水平居中 */
	  font-size: 18px;
	  font-weight: bold;
	  margin-left: -20px;
	}
	.chat-messages {
		flex: 1;
		padding: 10px;
		overflow-y: auto;
		background-color: #ffffff;
		margin-bottom: 20px;
	}

	.message-wrapper {
		display: flex;
		align-items: center;
		margin: 10px 0;
	}

	.customer-wrapper {
		font-size: 8px;
		display: flex;
		margin-bottom: 30rpx;
		margin-right: 10.px;
		justify-content: flex-start;
	}

	.agent-wrapper {
		font-size: 8px;
		display: flex;
		margin-bottom: 30rpx;
		justify-content: flex-end;
	}

	.avatar {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		margin: 0 10px;
	}

	.message {
		max-width: 70%;
		padding: 10px;
		border-radius: 10px;
	}

	.customer {
		background-color: #2ac2d2;
		color: #fff;
	}

	.agent {
		background-color: #eeeeee;
		color: #333;
	}

	.message-text {
		font-size: 14px;
		line-height: 1.4;
	}

	/* 输入框和发送按钮样式 */
	.input-container {
		display: flex;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 10px;
		background-color: #ffffff;
		border-top: 1px solid #ddd;
		box-shadow: 0px -2px 4px rgba(0, 0, 0, 0.1);
	}

	.message-input {
		flex: 1;
		padding: 10px;
		border: 1px solid #ddd;
		border-radius: 20px;
		font-size: 16px;
	}

	.send-button {
		padding: 10px 20px;
		margin-left: 10px;
		background-color: #2ac2d2;
		color: #fff;
		border-radius: 20px;
		font-size: 16px;
	}
</style>